package com.quyeying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quyeying.entity.TblAddressEntity;
import com.quyeying.entity.TblUserEntity;
import com.quyeying.mapper.TblAddressDao;
import com.quyeying.service.TblAddressService;
import com.quyeying.service.TblUserService;
import com.quyeying.utils.TokenUtil;
import com.quyeying.utils.httputils.HttpUtil;
import com.quyeying.utils.result.R;
import com.quyeying.utils.result.ResultEnum;
import com.quyeying.utils.result.ReturnPageData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
* <p>
 *  服务实现类
 * </p>
*
* @author jll
* @since 2022-07-25
*/
@Service
public class TblAddressServiceImpl extends ServiceImpl<TblAddressDao, TblAddressEntity> implements TblAddressService {

    @Resource
    private TblAddressDao tblAddressDao;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Resource
    ObjectMapper objectMapper;
    @Resource
    private TblUserService tblUserService;


    @Override
    public R findListByPage(Integer page, Integer pageCount, HttpServletRequest request){
        long userId = TokenUtil.getUserId(request);
        IPage<TblAddressEntity> wherePage = new Page<>(page, pageCount);
        TblAddressEntity where = new TblAddressEntity();
        where.setUserId(userId);
        IPage<TblAddressEntity> iPage = baseMapper.selectPage(wherePage, Wrappers.query(where).orderByAsc("create_time"));
        return R.success(ReturnPageData.fillingData(iPage));
    }

    @Override
    public R add(TblAddressEntity tblAddressEntity,HttpServletRequest request){
        long userId = TokenUtil.getUserId(request);
        tblAddressEntity.setUserId(userId);
        baseMapper.insert(tblAddressEntity);
        return R.success();
    }

    @Override
    public R delete(Long id){
        baseMapper.deleteById(id);
        return R.success();
    }

    @Override
    public R updateData(TblAddressEntity tblAddressEntity,HttpServletRequest request){
        long userId = TokenUtil.getUserId(request);
        if (tblAddressEntity.getDefaultStatus()==1){
            UpdateWrapper<TblAddressEntity> addressEntityUpdateWrapper = new UpdateWrapper<>();
            addressEntityUpdateWrapper.eq("user_id", userId);
            TblAddressEntity update = new TblAddressEntity();
            update.setDefaultStatus(0);
            baseMapper.update(update, addressEntityUpdateWrapper);
        }
        baseMapper.updateById(tblAddressEntity);
        return R.success();
    }

    @Override
    public R findById(Long id){
        TblAddressEntity tblAddressEntity = baseMapper.selectById(id);
        return R.success(tblAddressEntity);
    }

    @Override
    public R findByIdOrDefault(Long id, HttpServletRequest request) {
        long userId = TokenUtil.getUserId(request);
        return R.success(tblAddressDao.findByIdOrDefault(id,userId));
    }

    @Override
    public R findByCodeDefault(String codes) throws JsonProcessingException {
        if (codes == null || codes.length() == 0) {
            return R.error(ResultEnum.SYSTEM_ERROR);
        }
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid
                +"&secret="+appSecret+"&js_code="+codes+"&grant_type=authorization_code";
        String result = HttpUtil.sendGetHttps(url, null);
        JsonNode jsonNode = objectMapper.readTree(result);

        if(!jsonNode.has("errcode")) {
            //根据登录用户得openid获取用户信息
            String openid = jsonNode.get("openid").asText();
            QueryWrapper<TblUserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openid", openid);
            TblUserEntity userEntity = tblUserService.getOne(queryWrapper);
            if (ObjectUtils.isNotEmpty(userEntity)){
                QueryWrapper<TblAddressEntity> addressEntityQueryWrapper = new QueryWrapper<>();
                addressEntityQueryWrapper.eq("user_id", userEntity.getId());
                List<TblAddressEntity> tblAddressEntities = tblAddressDao.selectList(addressEntityQueryWrapper);
                return R.success(tblAddressEntities);
            }
        }
        return R.error(ResultEnum.UNKNOWN_ERROR.getCode(), "获取地址失败");
    }
}
